require 'active_record'

$db_config={
  :adapter=>"sqlite3",
  :dbfile=>"../../bin/dq9d.db"
}

ActiveRecord::Base.establish_connection($db_config)

class Item < ActiveRecord::Base
end

class Alchemy < ActiveRecord::Base
end

results = []
alchemies = Alchemy.find(:all)
alchemies.each do |alchemy|
  product = Item.find(alchemy.product)
  sell = product.sell_price
  buys=[]
  names=[]
  result=0
  if sell == 0
    results << {:result=>0, :names=>[], :sell=>0, :buys=>[]}
    next
  end
  names << product.japaness_name
  
  material1 = Item.find(alchemy.material1)
  if material1.buy_price == 0
    results << {:result=>0, :names=>[], :sell=>0, :buys=>[]}
    next
  end
  names << material1.japaness_name
  buys << {:price=>material1.buy_price, :num=>alchemy.num1}
  
  unless alchemy.material2 == 0
    material2 = Item.find(alchemy.material2)
    if material2.buy_price == 0
      results << {:result=>0, :names=>[], :sell=>0, :buys=>[]}
      next
    end
    names << material2.japaness_name
    buys << {:price=>material2.buy_price, :num=>alchemy.num2}
  end
  unless alchemy.material3 == 0
    material3 = Item.find(alchemy.material3)
    if material3.buy_price == 0
      results << {:result=>0, :names=>[], :sell=>0, :buys=>[]}
      next
    end
    names << material3.japaness_name
    buys << {:price=>material3.buy_price, :num=>alchemy.num3}
  end
    result = sell
    buys.each { |buy| result -= buy[:price]*buy[:num] }
    results << {:result=>result, :names=>names, :sell=>sell, :buys=>buys}
end

def show_results(results)
  results.each do |result|
    next if result[:result]==0
    buy_price = 0
    result[:buys].each { |buy| buy_price += buy[:price]*buy[:num] }
    puts "result: #{result[:result]} = #{result[:sell]} - #{buy_price}"
    puts result[:names].join(" - ")
  end
end

results.sort! { |x,y| y[:result] <=> x[:result] }

show_results(results)

